package com.jxwifi.cloud.quickclean.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.basicactivity.BasicFrgment;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.adapter.ClientMyOrderListAdapter;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.OrderBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.orderdetails.OrderDetailsActivity;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.view.SuperSwipeRefreshLayout;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class CleaningOrderFragment extends BasicFrgment {


    @Bind(R.id.srl_my_order_list)
    SuperSwipeRefreshLayout mSrlMyOrderList;
    @Bind(R.id.rv_my_order_list)
    RecyclerView mRvMyOrderList;


    private ClientMyOrderListAdapter mAdapter;
    private boolean mNoData = true;
    private int mPageIndex = 1;
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）
    private int mCurrentCounter;//获取的数据个数
    private boolean isErr = true;

    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    private View notDataView;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fg_cleaning_order_listview, container, false);
        ButterKnife.bind(this, root);
        openEventBus();
        initView();
        Refresh();

        return root;
    }

    public void initView() {
        mRvMyOrderList.setLayoutManager(new LinearLayoutManager(mBaseContext));
        mRvMyOrderList.setAdapter(mAdapter = new ClientMyOrderListAdapter(R.layout.list_my_order_item));
        mAdapter.openLoadAnimation();
        mAdapter.openLoadAnimation(BaseQuickAdapter.FOOTER_VIEW);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.lin_list_my_order:
                        Intent intent=new Intent();
                        intent.setClass(mBaseContext, OrderDetailsActivity.class);
                        intent.putExtra("order_code",mAdapter.getData().get(position).getOrderCode());
                        startActivity(intent);
                        break;
                }
            }
        });
        //上拉加载更多操作
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mRvMyOrderList.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentCounter >= mTotalNum) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                        } else {
                            if (isErr) {
                                getData();
                                //成功获取更多数据
                                mCurrentCounter = mAdapter.getData().size();
                                mAdapter.loadMoreComplete();
                            } else {
                                //获取更多数据失败
                                isErr = true;
                                Toast.makeText(mBaseContext, "获取更多数据失败", Toast.LENGTH_LONG).show();
                                mAdapter.loadMoreFail();
                            }
                        }
                    }
                }, 1500);

            }
        }, mRvMyOrderList);
        mSrlMyOrderList.setHeaderView(createHeaderView());
        mSrlMyOrderList.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mSrlMyOrderList.setRefreshing(false);
                        progressBar.setVisibility(View.GONE);
                        mPageIndex = 1;
                        getData();
                    }
                }, 1000);
            }

            @Override
            public void onPullDistance(int distance) {
                // pull distance
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });
    }



    public void getData() {
        Params params = new Params();
        params.add("limit", 10);
        params.add("page", mPageIndex);
        new AuzImpl().auzget(UrlPool.GET_LIST_CUSTIMER, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    String str = obj.getString("records");
                    mTotalNum = obj.getInteger("total");
                    List<OrderBean> mrecords = JSON.parseArray(str, OrderBean.class);
                    if (mPageIndex == 1) {
                        setData(true, mrecords);
                    } else {
                        setData(false, mrecords);
                    }
                } else {
                    getData();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                isErr = false;
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
            }
        });
    }

    public void Refresh() {
        mAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) mRvMyOrderList.getParent());
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mNoData) {
                    mPageIndex = 1;
                    getData();
                } else {
                    mAdapter.setEmptyView(getViews());
                }
            }
        }, 1000);
    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(mSrlMyOrderList.getContext())
                .inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.down_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;

    }

    public View getViews() {
        notDataView = getLayoutInflater().inflate(R.layout.null_layout, (ViewGroup) mRvMyOrderList.getParent(), false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Refresh();
            }
        });
        return notDataView;
    }

    public void setData(boolean isRefresh, List data) {
        mPageIndex++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (data == null || data.size() == 0) {
                mNoData = false;
                mSrlMyOrderList.setEnabled(false);
                mAdapter.setEmptyView(getViews());
            } else {
                mSrlMyOrderList.setEnabled(true);
                mAdapter.setNewData(data);
            }
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        mCurrentCounter = mAdapter.getData().size();
        if (size < mPageIndex) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }
}
